import time

from django.utils import timezone
from celery import shared_task

from app.models import City, Host, HostRecord, MachineRoom
from utils.pwd import generate_password, encrypt_password


def update_host_password(host_id):
    """更新密码"""
    try:
        host = Host.objects.get(id=host_id)
        new_password = generate_password()
        host.host_password = encrypt_password(new_password)
        host.save()

        return {
            "status": "success",
            "host_id": host_id,
            "hostname": host.hostname,
            "change_time": timezone.now().isoformat()
        }

    except Host.DoesNotExist:
        return {"status": "error", "message": f"主机ID {host_id} 不存在"}


@shared_task
def batch_update_host_passwords():
    """批量更新所有主机的密码"""
    hosts = Host.objects.filter()
    results = []
    for host in hosts:
        result = update_host_password(host.id)
        results.append({
            "host_id": host.id,
            "hostname": host.hostname,
            "result": result
        })
        time.sleep(1)

    return {
        "total": hosts.count(),
        "updated": len(results),
        "results": results
    }


@shared_task
def statistic_hosts():
    """统计主机数量"""
    today = timezone.now().date()
    statistics = []

    for city in City.objects.all():
        for room in MachineRoom.objects.filter(city=city):
            host_count = Host.objects.filter(machine=room).count()
            stat, created = HostRecord.objects.update_or_create(
                city=city,
                machine_room=room,
                record_date=today,
                defaults={"host_count": host_count}
            )

            statistics.append({
                "city": city.name,
                "machine_room": room.name,
                "host_count": host_count,
                "created": created
            })

    return {
        "statistic_date": today.isoformat(),
        "total_records": len(statistics),
        "details": statistics
    }
